package com.itsu.graph_v2.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itsu.graph_v2.entity.Result;
import com.itsu.graph_v2.entity.User;
import com.itsu.graph_v2.service.UserService;
import com.netflix.graphql.dgs.*;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@DgsComponent
public class UserComponent {

    @Autowired
    UserService userService;

    @DgsQuery
    public List<User> users(@InputArgument Integer id) {
        List<User> users = userService.findAll();

        if (ObjectUtils.isEmpty(id)) {
            return users;
        }

        return users.stream().filter(user -> user.getId() == id).collect(Collectors.toList());
    }

    @DgsData(parentType = "Mutation", field = "addUser")
    public Result addUser(@InputArgument String name, @InputArgument Integer age) {
        User user = User.builder().name(name).age(age).build();
        int i = userService.addUser(user);
        if (i == 0) {
            return new Result(500, "操作失败");
        }

        return new Result(200, "操作成功");
    }

    @DgsData(parentType = "Mutation", field = "addUserByUser")
    public Result addUserByUser(DataFetchingEnvironment df) {
        Map<String, Object> input = df.getArgument("input");
        User user = new ObjectMapper().convertValue(input, User.class);
        int i = userService.addUser(user);
        if (i == 0) {
            return new Result(500, "操作失败");
        }

        return new Result(200, "操作成功");
    }


    @DgsData(parentType = "Mutation", field = "updateUser")
    public Result updateUser(DataFetchingEnvironment df) {
        Map<String, Object> input = df.getArgument("input");
        User user = new ObjectMapper().convertValue(input, User.class);

        int i = userService.updateUser(user);
        if (i == 0) {
            return new Result(500, "操作失败");
        }

        return new Result(200, "操作成功");
    }


    @DgsData(parentType = "Mutation", field = "deleteUser")
    public Result deleteUser(@InputArgument Integer id) {
        if (ObjectUtils.isEmpty(id)) {
            return new Result(500, "参数不能为空");
        }
        int i = userService.deleteUser(id);
        if (i == 0) {
            return new Result(500, "操作失败");
        }

        return new Result(200, "操作成功");
    }


}
